# Definition for singly-linked list.
from typing import Optional


class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
        if head.next is None or left == right:
            return head
        dummy = ListNode(0)
        dummy.next = head
        for _ in range(left-1):
            dummy = dummy.next
        # 此时dummy就是left位置的前一个节点

        cur = dummy.next
        aaa = cur
        bbb = head
        for _ in range(right):
            bbb = bbb.next

        pre=bbb
        for _ in range(left, right):
            tmp = cur.next
            cur.next = pre
            pre = cur
            cur = tmp
        dummy.next = cur

        aaa.next = bbb
        return head
